package com.andy.contentcenter.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <B>系统名称：</B>学习<BR>
 * <B>模块名称：</B><BR>
 * <B>中文类名：</B><BR>
 * <B>概要说明：</B><BR>
 *
 * @author wsr
 * @since Created in 2019/9/4 13:27
 */
@Slf4j
@RestController
public class TestController {

    @GetMapping("/test-sentinel-api")
    public String testSentinelAPI(@RequestParam(required = false) String a){

        //保护的资源名称
        String resourceName = "test-sentinel-api";
        //标记调用来源以及调用
        ContextUtil.enter(resourceName,"test-wfw");
        Entry entry =null;
        //定义一个sentinel保护的资源，名称是test-sentinel-api
        try {
            entry = SphU.entry(resourceName);
            //被保护的业务逻辑
            if (StringUtils.isBlank(a)){
                throw new IllegalArgumentException("a不能为空");
            }
            return a;
        }
        //如果被保护的资源被限流或者降级了，就被抛BlockException
        catch (BlockException e) {
            log.warn("限流，或者降级了",e);
            return "限流，或者降级了";
        } catch (IllegalArgumentException e2) {
            //统计IllegalArgumentException [发生的次数，发生占比。。]
            Tracer.trace(e2);
            return "非法参数！";
        }finally {
            //关闭entry,ContextUtil
            if (entry != null){
                entry.exit();
            }
            ContextUtil.exit();
        }

    }

    @GetMapping("/testSentinelResource")
    @SentinelResource(value = "test-sentinel-api",blockHandler = "block",fallback = "fallback")
    public String testSentinelResource(@RequestParam(required = false) String a){
        if (StringUtils.isBlank(a)){
            throw new IllegalArgumentException("a can't be null");
        }
        return a;
    }

    /**
     *  处理限流或者降级
     * @author wsr
     * @since Created in ${DATE} ${TIME}
     */

    public String block(String a,BlockException e){
        log.warn("限流，或者降级了",e);
        return "限流，或者降级了 block";
    }
    /**
     * 1.5处理降级
     * - sentinel 1.6 可以处理Throwable
     * @author wsr
     * @since Created in ${DATE} ${TIME}
     */
    public String fallback(String a){
        return "限流，或者降级了 fallback";
    }
}
